<template>
  <lay-card>
    <lay-form :model="pushParams" :pane="false" :label-position="labelPosition" required>
      <lay-line>推送策略基本信息</lay-line>
      <lay-row space="5">
        <lay-col md="12">
          <lay-form-item size="sm" label="场景" mode="inline" prop="sceneName">
            <lay-input v-model="pushParams.sceneName" size="sm" placeholder="请输入" class="inputDiv"></lay-input>
          </lay-form-item>
        </lay-col>
        <lay-col md="12">
          <lay-form-item size="sm" label="描述" mode="inline">
            <lay-input v-model="pushParams.description" size="sm" placeholder="请输入" class="inputDiv"></lay-input>
          </lay-form-item>
        </lay-col>
      </lay-row>
      <lay-line><span class="linePos">行情消息筛选条件</span></lay-line>
      <lay-row space="5">
        <lay-col md="12">
          <lay-form-item size="sm" label="市场" mode="inline" prop="market">
            <lay-select
                size="sm"
                v-model="pushParams.market"
                placeholder="请选择"
                class="inputDiv"
            >
              <lay-select-option :value="item.value" :label="item.value" v-for="item in markets"></lay-select-option>
            </lay-select>
          </lay-form-item>
        </lay-col>
        <lay-col md="12">
          <lay-form-item size="sm" label="行情源" mode="inline" prop="protocol">
            <lay-select
                size="sm"
                v-model="pushParams.protocol"
                @change="exchangeProtocol"
                placeholder="请选择"
                class="inputDiv"
            >
              <lay-select-option :value="item.value" :label="item.name" v-for="item in protocols"></lay-select-option>
            </lay-select>
          </lay-form-item>
        </lay-col>
        <lay-col md="24">
          <lay-form-item size="sm" label="时间" mode="inline" prop="rangeTime">
            <lay-date-picker
               size="sm"
               v-model="rangeTime"
               range
               type="datetime"
               :placeholder="['开始日期','结束日期']"
               style="width: 520px"
            ></lay-date-picker>
          </lay-form-item>
        </lay-col>
        <lay-col md="12">
          <lay-form-item size="sm" label="行情类型" mode="inline">
            <lay-select
                size="sm"
                v-model="pushParams.types"
                placeholder="请选择"
                class="inputDiv"
                multiple
                allow-clear
            >
              <lay-select-option :value="item.value" :label="item.name" v-for="item in mysTypes"></lay-select-option>
            </lay-select>
          </lay-form-item>
        </lay-col>
        <lay-col md="12">
          <lay-form-item size="sm" label="行情类别" mode="inline">
            <lay-input v-model="pushParams.mdStreamId" size="sm" placeholder="请输入" class="inputDiv"></lay-input>
          </lay-form-item>
        </lay-col>
        <lay-col md="12">
          <lay-form-item size="sm" label="证券代码" mode="inline">
            <lay-input v-model="pushParams.securityId" size="sm" placeholder="请输入" class="inputDiv"></lay-input>
          </lay-form-item>
        </lay-col>
      </lay-row>
      <lay-line><span class="linePos">数据推送配置</span></lay-line>
      <lay-row space="5">
        <lay-col md="12">
          <lay-form-item size="sm" label="推送模式" mode="inline" prop="pushMode">
            <lay-select size="sm" v-model="pushParams.pushMode" placeholder="请选择" class="inputDiv" @change="changePushMode">
              <lay-select-option :value="item.value" :label="item.name" v-for="item in pushModeTypes"></lay-select-option>
            </lay-select>
          </lay-form-item>
        </lay-col>
        <lay-col md="12" v-if="pushParams.pushMode === '2'">
          <lay-form-item size="sm" label="推送频率" mode="inline">
            <lay-select size="sm" v-model="pushParams.pushFrequency" placeholder="请选择" class="inputDiv">
              <lay-select-option :value="item.value" :label="item.name" v-for="item in pushFreq"></lay-select-option>
            </lay-select>
          </lay-form-item>
        </lay-col>
        <lay-col md="12" v-if="pushParams.pushMode === '3'">
          <lay-form-item size="sm" label="积压数量" mode="inline">
            <lay-select size="sm" v-model="pushParams.pushCondition" placeholder="请选择" class="inputDiv">
              <lay-select-option :value="item.value" :label="item.name" v-for="item in pushTopNumber"></lay-select-option>
            </lay-select>
          </lay-form-item>
        </lay-col>
      </lay-row>
      <lay-line><span class="linePos">定时任务配置</span></lay-line>
      <lay-row space="10">
        <lay-col md="12">
          <lay-form-item size="sm" label="是否定时" prop="cornJob">
            <lay-switch size="sm" v-model="pushParams.cornJob" onswitch-text="是"  unswitch-text="否"></lay-switch>
          </lay-form-item>
        </lay-col>
        <lay-col md="12">
          <lay-form-item v-if="pushParams.cornJob" size="sm" label="Cron">
            <lay-input v-model="pushParams.cornTime" size="sm" placeholder="示例 00 48 11 * * ? " class="inputDiv">
              <template #append="{disabled}"><lay-icon type="layui-icon-help" @click="viewHelp"></lay-icon></template>
            </lay-input>
          </lay-form-item>
        </lay-col>
      </lay-row>
      <lay-line></lay-line>
      <lay-row space="5">
        <lay-col md="24">
          <lay-form-item style="text-align: center;">
            <lay-button type="normal" @click="addFilterParams" size="sm">保存</lay-button>
          </lay-form-item>
        </lay-col>
      </lay-row>
    </lay-form>
  </lay-card>
</template>

<script lang="ts">
export default {
  name: 'PushParams'
}
</script>

<script setup lang="ts">
import {onBeforeMount, ref} from "vue";
import {addStrategy, getClientList, updateStrategy} from "../../api/market/market";
import {notify} from "../../untils/tip";
import {getConfig} from "../../api/market/basic";
import {layer} from "@layui/layui-vue";


const {address, rowParams} = defineProps({
  address: {type: String, default: null},
  rowParams: {type: Object, default: null}
});

const emit = defineEmits(["cancel"]);

const labelPosition = ref('right');

// 推送策略的参数
const rangeTime = ref([]);
const pushParams = ref({
    rowId: null,
    sceneName: null,
    targetClient: '',
    // 以下3个参数用于定位选择行情数据源
    industry: null,
    market: null,
    protocol: null,
    // 以下参数是行情数据筛选条件的入参
    beginTime: '',
    endTime: '',
    types: [],
    msgType: '',
    securityId: null,
    mdStreamId: null,
    // 定时任务
    cornJob: false,    // 是否定时任务
    cornTime: '',   // 定时任务的时间
    // 推送模式 1：即时消费模式  2：频率控制模式   3：峰谷批量触发模式
    pushMode: '1',
    pushCondition: null,
    pushFrequency: 0,
    description: null,
    mockDate: '',
    // 预留字段
    extField1: null,
    extField2: null,
    extField3: null,
    // 筛选数据的limit参数，不会存库
    pageSize: 10000
});

const mysTypes : any = ref([]);
const markets: any = ref([]);
const protocols: any = ref([]);
const linkedClients = ref([]);
const pushModeTypes = ref([]);
const pushFreq = ref([]);
const pushTopNumber = ref([]);


// 函数方法,初始化
onBeforeMount(()=>{
  // queryLinkedClients();
  getSelectItems('market');
  getSelectItems('protocol');
  getSelectItems('msgTypes');
  getSelectItems('push_mode');
  setInitParams();
  changePushMode();
});

// 初始化
const setInitParams = () => {
  // rowId 不为空，则更新，否则为新增
  if (rowParams) {
    if (rowParams.rowId !== null) {
      console.log("rowParams:", rowParams)
      console.log("pushParams1:", pushParams.value)
      pushParams.value.rowId = rowParams.rowId;
      pushParams.value.sceneName = rowParams.sceneName;
      pushParams.value.targetClient = rowParams.targetClient;
      // 以下3个参数用于定位选择行情数据源
      pushParams.value.industry = rowParams.industry;
      pushParams.value.market = rowParams.market;
      pushParams.value.protocol = rowParams.protocol;
      // 以下参数是行情数据筛选条件的入参
      rangeTime.value = [];
      rangeTime.value.push(rowParams.beginTime);
      rangeTime.value.push(rowParams.endTime);
      pushParams.value.beginTime = rowParams.beginTime;
      pushParams.value.endTime = rowParams.endTime;
      // 行情消息类型，需要将 字符串 转换成 数组
      pushParams.value.msgType = rowParams.msgType;
      if (rowParams.msgType && rowParams.msgType.length > 0) {
        pushParams.value.types = rowParams.msgType.split(',');
      }
      pushParams.value.securityId = rowParams.securityId;
      pushParams.value.mdStreamId = rowParams.mdStreamId;
      // 定时任务
      pushParams.value.cornJob = rowParams.cornJob;    // 是否定时任务
      pushParams.value.cornTime = rowParams.cornTime;   // 定时任务的时间
      // 推送模式 1：即时消费模式  2：频率控制模式   3：峰谷批量触发模式
      pushParams.value.pushMode = rowParams.pushMode;
      pushParams.value.pushCondition = rowParams.pushCondition;
      pushParams.value.pushFrequency = rowParams.pushFrequency;
      pushParams.value.description = rowParams.description;
      pushParams.value.mockDate = rowParams.mockDate;
      console.log("pushParams2:", pushParams.value)
    } else {
      // 新增
      if (address) {
        pushParams.value.targetClient = address;
      }
    }
  } else {
    // 新增
    if (address) {
      pushParams.value.targetClient = address;
    }
  }

};

// 切换推送模式触发
const changePushMode = () => {
  if(pushParams.value.pushMode === '2'){
    getSelectItems('push_freq');
  }else if(pushParams.value.pushMode === '3'){
    getSelectItems('push_top');
  }else {
    console.log('不请求')
  }
};

const exchangeProtocol = () => {
  if(pushParams.value.protocol !== null && pushParams.value.protocol === "binary"){
    getSelectItems("msgTypes");
  }else {
    getSelectItems("stepMsgTypes");
  }
};


// 获取下拉列表选择的值
const getSelectItems = async (target: string) => {
  let {data, code, message} = await getConfig({target: target})
  if(code === 200){
    switch (target) {
      case 'msgTypes': mysTypes.value = data; break;
      case 'stepMsgTypes': mysTypes.value = data; break;
      case 'market': markets.value = data; break;
      case 'protocol': protocols.value = data; break;
      case 'push_mode': pushModeTypes.value = data; break;
      case 'push_freq': pushFreq.value = data; break;
      case 'push_top': pushTopNumber.value = data; break;
    }
  }else {
    notify('fail', message);
  }
};

// 查询活跃的客户端列表
const queryLinkedClients = async () => {
  let {data, code, message} = await getClientList({refresh: false});
  if(code === 200 && data !== null){
    linkedClients.value = data;
  }else {
    notify('fail', "获取客户端失败！");
  }
};

// 参数处理和检查
const checkParams = (): boolean => {
  if(pushParams.value.sceneName === null){
    layer.msg("请给该场景命名，方便记忆和筛选！", {icon: 7, time: 1000});
    return false;
  }
  if(pushParams.value.protocol === null){
    layer.msg("请选择行情源！", {icon: 7, time: 1000});
    return false;
  }
  if(rangeTime.value.length === 2){
    pushParams.value.beginTime = rangeTime.value[0];
    pushParams.value.endTime = rangeTime.value[1];
  }else {
    layer.msg("请选择筛选的起始/终止时间！", {icon: 7, time: 1000});
    return false;
  }
  if(pushParams.value.types.length > 0){
    pushParams.value.msgType = pushParams.value.types.toString();
  }else {
    pushParams.value.msgType = "";
  }
  return true;
};


const viewHelp = function() {
    layer.open({
        type: 2,
        resize: true,
        offset: ['5%', '15%'],
        area: ['60%','80%'],
        title: "Cron表达式工具",
        zIndex: 200001,
        content: "https://cron.qqe2.com"
    })
};

// 新增策略
const addFilterParams = async () => {
  if(checkParams()){
    if(pushParams.value.rowId === null){
      let {data, code, message} = await addStrategy(pushParams.value);
      if(code === 200 && data !== null){
        notify('success', "新增策略，" + message);
        cancelAction();
      }else {
        notify('fail', "新增策略失败！");
      }
    }else {
      let {data, code, message} = await updateStrategy(pushParams.value);
      if(code === 200 && data !== null){
        notify('success', "更新策略，" + message);
        cancelAction();
      }else {
        notify('fail', "更新策略失败！");
      }
    }
  }else {
    notify('fail', "补齐必填项后再试！");
  }
};


// 取消操作，子组件触发父组件的方法
const cancelAction = () => {
  emit('cancel');
};

</script>

<style scoped>
.inputDiv {
  width: 100%;
}

.linePos {
  height: 1px
}

.keyContent {
  font-size: medium;
  color: crimson;
}
</style>